package com.ruoyi.AIAPI;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class XModel {
    // 获取地址 https://console.xfyun.cn/services/cbm
    public static String APIPassword = "sYEXKAudpglQJMbVPptS:iFtTzVjBpUafreooofdj";
    public StringBuilder getAI( String temp) {
        String userId = "10284711用户";
        try {
            String url = "https://spark-api-open.xf-yun.com/v2/chat/completions";

            // 创建最外层的JSON对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("user", userId);
            jsonObject.put("model", "x1");
            // 创建messages数组
            JSONArray messagesArray = new JSONArray();
            // 创建单个消息的JSON对象
            JSONObject messageObject = new JSONObject();
            System.err.println(temp);
            messageObject.put("role", "user");
            messageObject.put("content", temp);
            messageObject.put("temperature", "0.5");
            // 将单个消息对象添加到messages数组中
            messagesArray.add(messageObject);

            // 将messages数组添加到最外层的JSON对象中
            jsonObject.put("messages", messagesArray);
            // 设置stream属性为true
            jsonObject.put("stream", true);
            jsonObject.put("max_tokens", 4096);
            // System.err.println(jsonObject);

            String header = "Authorization: Bearer" + APIPassword; // 注意此处替换自己的key和secret

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Authorization", header);
            con.setDoOutput(true);

            OutputStream os = con.getOutputStream();
            os.write(jsonObject.toString().getBytes());
            os.flush();
            os.close();

            int responseCode = con.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            List<JSONObject> responses = new ArrayList<>();
            StringBuilder contentBuilder = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                if (inputLine.startsWith("data: ")) {
                    String jsonStr = inputLine.substring(6).trim();
                    if (!jsonStr.equals("[DONE]")) {
                        try {
                            JSONObject json = JSONObject.parseObject(jsonStr);
                            responses.add(json);

                            // 提取 reasoning_content
                            JSONArray choices = json.getJSONArray("choices");
                            if (choices != null && !choices.isEmpty()) {
                                JSONObject choice = choices.getJSONObject(0);
                                JSONObject delta = choice.getJSONObject("delta");
                                if (delta != null) {
                                    String reasoningContent = delta.getString("reasoning_content");
                                    if (reasoningContent != null) {
                                        contentBuilder.append(reasoningContent);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            // 忽略解析错误
                        }
                    }
                }
            }

            System.out.println("完整响应: " + responses);
            System.out.println("提取的内容: " + contentBuilder.toString());

            return contentBuilder;
        } catch (Exception e) {
            return null;
        }
    }
}